package com.rui.sideup.module.udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author ZhangRui
 * @date 2022/12/14 13:08
 **/
public class UdpClient {

    DatagramSocket socket;

    public void open() {
        // 20020是本机的端口号
        try {
            if (socket == null) {
                socket = new DatagramSocket();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void sendMsg(String message) {
        try {
            if (socket == null) {
                open();
            }
            //将字符串转换成字节流，因为底层的传输都是字节传输
            byte data[] = message.getBytes();

            // 对方的IP和端口号
            // 创建DatagramPacket 对象数据包，这里的60000是我们要发送信息主机的端口号
            DatagramPacket pack = null;

            pack = new DatagramPacket(data, data.length,
                    InetAddress.getByName("255.255.255.255"),
                    9981);

            socket.send(pack);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("发送成功=>" + message);

    }
}
